﻿/*
************* 创建共享内存通讯 ***************
*/

#include <iostream>
#include <string>
#include <thread>
#include <Windows.h>

#define MEM_SIZE	256

using namespace std;

int main()
{
	// 创建一个共享内存句柄
	HANDLE hMapFile = CreateFileMapping(
		INVALID_HANDLE_VALUE,
		NULL,
		PAGE_READWRITE,
		0,
		MEM_SIZE,
		L"TestSharedMemory"
	);

	if (hMapFile == NULL)
	{
		cout << "没有正确获取到共享内存句柄" << endl;
		return -1;
	}

	// lpBase指向这个内存
	LPVOID lpBase = MapViewOfFile(
		hMapFile,
		FILE_MAP_ALL_ACCESS,
		0,
		0,
		MEM_SIZE
	);

	if (lpBase == NULL)
	{
		cout << "没有正确获取到共享内存指针" << endl;
		return -1;
	}

	// 构建一个Hello World，存入内存中
	string send = "Hello World";
	memcpy_s(lpBase, MEM_SIZE, send.data(), send.length());

	Sleep(100000);

	// 别忘记释放内存和句柄
	UnmapViewOfFile(lpBase);
	CloseHandle(hMapFile);
}

